<?php

namespace app\admin\model;

use think\Model;


class Agent extends Model
{

    

    

    // 表名
    protected $name = 'agent';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'status_text',
        'create_time_text'
    ];
    
    public function getOriginData()
    {
        return $this->origin;
    }
    protected static function init()
    {
        self::beforeUpdate(function ($row) {
            $changed = $row->getChangedData();
            $origin = $row->getOriginData();
            //如果修改成通过
            if ($changed['status'] == 1) {
                User::where('id',$origin['user_id'])->update(['agent_id' => $origin['id']]);
            }
        });


       
    }
    public function getStatusList()
    {
        return ['0' => __('Status 0'), '1' => __('Status 1'), '2' => __('Status 2')];
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ?: ($data['status'] ?? '');
        $list = $this->getStatusList();
        return $list[$value] ?? '';
    }


    public function getCreateTimeTextAttr($value, $data)
    {
        $value = $value ?: ($data['create_time'] ?? '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setCreateTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }
    /**
     * 完整身份证验证
     * @param string $idCard
     * @return array|bool
     */
    public  function validateIdCardComplete($idCard) {
        // 基础格式验证
        if (!$this->validateIdCard($idCard)) {
            return false;
        }
        
        // 地区码验证
        $areaCode = substr($idCard, 0, 6);
        if (!$this->validateAreaCode($areaCode)) {
            return false;
        }
        
        // 生日验证
        $birthday = substr($idCard, 6, 8);
        if (!$this->validateBirthday($birthday)) {
            return false;
        }
        return true;
        return [
            'valid' => true,
            'area' => $areaCode,
            'birthday' => $birthday,
            'gender' => $this->getGenderFromIdCard($idCard),
            'age' => $this->getAgeFromIdCard($idCard)
        ];
    }
    function validateIdCard($idCard) {
        // 基本格式验证
        if (!preg_match('/^\d{17}[\dXx]$/', $idCard)) {
            return false;
        }
        
        // 长度验证
        if (strlen($idCard) !== 18) {
            return false;
        }
        
        // 前17位必须是数字
        $first17 = substr($idCard, 0, 17);
        if (!ctype_digit($first17)) {
            return false;
        }
        
        // 校验码验证
        return $this->validateCheckCode($idCard);
    }
        /**
         * 验证地区码（简化版，实际应使用完整的地区码表）
         */
        public function validateAreaCode($areaCode) {
            // 这里可以扩展为完整的地区码验证
            $validPrefixes = ['11', '12', '13', '14', '15', '21', '22', '23', 
                            '31', '32', '33', '34', '35', '36', '37', '41', 
                            '42', '43', '44', '45', '46', '50', '51', '52', 
                            '53', '54', '61', '62', '63', '64', '65'];
            
            $prefix = substr($areaCode, 0, 2);
            return in_array($prefix, $validPrefixes);
        }
        
        /**
         * 验证身份证校验码
         * @param string $idCard
         * @return bool
                    */
            public function validateCheckCode($idCard) {
                if (strlen($idCard) !== 18) {
                    return false;
                }
                
                // 加权因子
                $factors = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
                
                // 校验码对应值
                $checkCodes = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];
                
                $sum = 0;
                for ($i = 0; $i < 17; $i++) {
                    $sum += intval($idCard[$i]) * $factors[$i];
                }
                
                $mod = $sum % 11;
                $checkCode = $checkCodes[$mod];
                
                return strtoupper($idCard[17]) === $checkCode;
            }

        /**
         * 验证生日格式
         */
        public function validateBirthday($birthday) {
            if (strlen($birthday) !== 8 || !ctype_digit($birthday)) {
                return false;
            }
            
            $year = intval(substr($birthday, 0, 4));
            $month = intval(substr($birthday, 4, 2));
            $day = intval(substr($birthday, 6, 2));
            
            // 基本范围验证
            if ($year < 1900 || $year > date('Y')) {
                return false;
            }
            
            if ($month < 1 || $month > 12) {
                return false;
            }
            
            if ($day < 1 || $day > 31) {
                return false;
            }
            
            // 日期有效性验证
            return checkdate($month, $day, $year);
        }

    /**
     * 从身份证获取性别
     */
    public function getGenderFromIdCard($idCard) {
        $genderCode = intval(substr($idCard, 16, 1));
        return $genderCode % 2 === 0 ? '女' : '男';
    }

    /**
     * 从身份证获取年龄
     */
    public function getAgeFromIdCard($idCard) {
        $birthday = substr($idCard, 6, 8);
        $birthYear = intval(substr($birthday, 0, 4));
        $birthMonth = intval(substr($birthday, 4, 2));
        $birthDay = intval(substr($birthday, 6, 2));
        
        $now = time();
        $currentYear = date('Y', $now);
        $currentMonth = date('m', $now);
        $currentDay = date('d', $now);
        
        $age = $currentYear - $birthYear;
        
        // 如果当前月日小于出生月日，年龄减1
        if ($currentMonth < $birthMonth || 
            ($currentMonth == $birthMonth && $currentDay < $birthDay)) {
            $age--;
        }
        
        return $age;
    }

}
